package com.example.humanresources.slice;

import com.example.humanresources.ResourceTable;
import com.example.humanresources.Utils;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.utils.net.Uri;

import ohos.data.resultset.ResultSet;

import java.io.*;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button mBtnEmployeeInsert; // 【增加员工信息】按钮
    private Button mBtnEmployeeQuery; // 【查询员工信息】按钮
    private Button mBtnEmployeeUpdate; // 【更新员工信息】按钮
    private Button mBtnEmployeeDelete; // 【删除员工信息】按钮
    private Button mBtnReadFile; // 【读取文件】按钮

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mBtnEmployeeInsert = (Button) findComponentById(ResourceTable.Id_btn_employee_insert);
        mBtnEmployeeInsert.setClickedListener(this);
        mBtnEmployeeQuery = (Button) findComponentById(ResourceTable.Id_btn_employee_query);
        mBtnEmployeeQuery.setClickedListener(this);
        mBtnEmployeeUpdate = (Button) findComponentById(ResourceTable.Id_btn_employee_update);
        mBtnEmployeeUpdate.setClickedListener(this);
        mBtnEmployeeDelete = (Button) findComponentById(ResourceTable.Id_btn_employee_delete);
        mBtnEmployeeDelete.setClickedListener(this);
        mBtnReadFile = (Button) findComponentById(ResourceTable.Id_btn_read_file);
        mBtnReadFile.setClickedListener(this);
    }

    @Override
    public void onClick(Component component) {

        // 定义URI
        Uri uri = Uri.parse("dataability:///com.example.employeemanager.EmployeeDataAbility");
        // 获得DataAbilityHelper对象
        DataAbilityHelper helper = DataAbilityHelper.creator(this);

        // 增加员工信息
        if (component.getId() == ResourceTable.Id_btn_employee_insert) {
            ValuesBucket values = new ValuesBucket();
            values.putString("name", "董昱");
            values.putInteger("age", 30);
            values.putInteger("sex", 1);
            values.putString("department", "董事会");

            try {
                int id = helper.insert(uri, values);
                if (id == -1) {
                    Utils.showToast(this, "数据插入失败!");
                } else {
                    Utils.showToast(this, "数据插入成功，Row ID: " + id + "!");
                }
            } catch (Exception e) {
                Utils.log("调用错误:" + e.getLocalizedMessage());
            }
        }

        // 查询员工信息
        if (component.getId() == ResourceTable.Id_btn_employee_query) {

            String[] columns = new String[]{"id", "name", "age", "sex", "department"};
            DataAbilityPredicates predicates = new DataAbilityPredicates()
                    .orderByAsc("id");
            ResultSet resultSet = null;
            try {
                resultSet = helper.query(uri, columns, predicates);
                Utils.log("结果集行数： " + resultSet.getRowCount());
                while (resultSet.goToNextRow()) {
                    int id = resultSet.getInt(0);
                    String name = resultSet.getString(1);
                    int age = resultSet.getInt(2);
                    int sex = resultSet.getInt(3);
                    String department = resultSet.getString(4);
                    Utils.log("id:" + id + " 姓名：" + name + " 年龄：" + age
                            + " 性别：" + (sex == 1 ? "男性" : "女性")
                            + " 部门：" + department);
                }
                // 关闭结果集
                resultSet.close();
            } catch (Exception e) {
                Utils.log("调用错误:" + e.getLocalizedMessage());
            }

        }

        // 更新员工信息
        if (component.getId() == ResourceTable.Id_btn_employee_update) {
            DataAbilityPredicates predicates = new DataAbilityPredicates()
                    .equalTo("name", "董昱");
            ValuesBucket values = new ValuesBucket();
            values.putString("department", "市场部");
            try {
                int rowNum = helper.update(uri, values, predicates);
                if (rowNum == -1) {
                    Utils.showToast(this, "数据更新失败!");
                } else {
                    Utils.showToast(this, "数据更新成功，更新行数: " + rowNum + "!");
                }
            } catch (Exception e) {
                Utils.log("调用错误:" + e.getLocalizedMessage());
            }
        }

        // 删除员工信息
        if (component.getId() == ResourceTable.Id_btn_employee_delete) {

            DataAbilityPredicates predicates = new DataAbilityPredicates()
                    .equalTo("name", "董昱");
            try {
                int rowNum = helper.delete(uri, predicates);
                if (rowNum == -1) {
                    Utils.showToast(this, "数据删除失败!");
                } else {
                    Utils.showToast(this, "数据删除成功，删除行数: " + rowNum + "!");
                }
            } catch (Exception e) {
                Utils.log("调用错误:" + e.getLocalizedMessage());
            }

        }

        // 创建文件
        if (component.getId() == ResourceTable.Id_btn_read_file) {

            // 定义URI
            uri = Uri.parse("dataability:///com.example.employeemanager.EmployeeDataAbility/test.txt");
            try {
                FileDescriptor fd = helper.openFile(uri, "rw");
                // 获得BufferedReader对象
                BufferedReader br = new BufferedReader(new FileReader(fd));
                // 获取文本内容
                String content = "";
                String line;
                while ((line = br.readLine()) != null) {
                    content += line;
                }
                br.close(); //关闭BufferedReader对象
                Utils.showToast(this, "文本内容:" + content);

            } catch (Exception e) {
                Utils.log("调用错误:" + e.getLocalizedMessage());
            }
        }
    }


}
